//
//  QRCodeViewController.m
//  NuwaRobot
//
//  Created by Kendama on 2017/12/4.
//  Copyright © 2017年 Kendama. All rights reserved.
//

#import "QRCodeViewController.h"
#import <CoreImage/CoreImage.h>
#import <SystemConfiguration/CaptiveNetwork.h>

@interface QRCodeViewController ()

@property(nonatomic,strong) UILabel *deviceLabel;
@property(nonatomic,strong) UIImageView *codeImageView;

@end

@implementation QRCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    
    CGRect extent = CGRectIntegral(image.extent);
    
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 创建bitmap;
    
    size_t width = CGRectGetWidth(extent) * scale;
    
    size_t height = CGRectGetHeight(extent) * scale;
    
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    
    CIContext *context = [CIContext contextWithOptions:nil];
    
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    
    CGContextScaleCTM(bitmapRef, scale, scale);
    
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 保存bitmap到图片
    
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    
    CGContextRelease(bitmapRef);
    
    CGImageRelease(bitmapImage);
    
    return [UIImage imageWithCGImage:scaledImage];
    
}

- (NSString *)getWifiName
{
    NSString *wifiName = nil;
    
    CFArrayRef wifiInterfaces = CNCopySupportedInterfaces();
    
    if (!wifiInterfaces) {
        return nil;
    }
    
    NSArray *interfaces = (__bridge NSArray *)wifiInterfaces;
    
    for (NSString *interfaceName in interfaces) {
        CFDictionaryRef dictRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interfaceName));
        
        if (dictRef) {
            NSDictionary *networkInfo = (__bridge NSDictionary *)dictRef;
            NSLog(@"network info -> %@", networkInfo);
            wifiName = [networkInfo objectForKey:(__bridge NSString *)kCNNetworkInfoKeySSID];
            
            CFRelease(dictRef);
        }
    }
    
    CFRelease(wifiInterfaces);
    return wifiName;
}

- (UILabel *)deviceLabel
{
    if(!_deviceLabel)
    {
        UIView *superView = self.view;
        _deviceLabel = [[UILabel alloc]init];
        [superView addSubview:_deviceLabel];
        [_deviceLabel setFont:fontCommonSize];
        [_deviceLabel setTextColor:[UIColor whiteColor]];
        _deviceLabel.numberOfLines = 0;
        _deviceLabel.textAlignment = NSTextAlignmentCenter;
        if ([self getWifiName])
        {
            _deviceLabel.text = @"将此二维码对准小天机器人\n即可帮助小天连上家庭WiFi网络";
        }
        else
        {
            _deviceLabel.text = @"请将手机连上WiFi";
        }
    }
    return _deviceLabel;
}

- (UIImageView *)codeImageView
{
    if(!_codeImageView)
    {
        UIView *superView = self.view;
        _codeImageView = [[UIImageView alloc]init];
        [superView addSubview:_codeImageView];
        CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
        // 2.恢复默认
        [filter setDefaults];
        // 3.给过滤器添加数据
        //    NSDictionary *mydic = @{@"uid":EXRACT_OBJECT(UID),@"token":EXRACT_OBJECT(TOKEN),@"mobile":EXRACT_OBJECT(USERNAME)};
        //    NSData *data=[NSJSONSerialization dataWithJSONObject:mydic options:NSJSONWritingPrettyPrinted error:nil];
        
        NSString *dataString = [self getWifiName];
        NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
        // 4.通过KVO设置滤镜inputMessage数据
        [filter setValue:data forKeyPath:@"inputMessage"];
        // 4.获取输出的二维码
        CIImage *outputImage = [filter outputImage];
        // 5.将CIImage转换成UIImage，并放大显示
        _codeImageView.image = [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:200];
    }
    return _codeImageView;
}


- (void)masLayoutSubview
{
    __weak UIView *superView = self.view;
    

    
    [self.codeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(px1920Height(397));
        make.centerX.mas_equalTo(superView.mas_centerX);
        make.height.width.mas_equalTo(px1920Height(365));
    }];
    
    [self.deviceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.codeImageView.mas_bottom).with.offset(px1920Height(80));
        make.centerX.mas_equalTo(superView.mas_centerX);
    }];
}

- (void)setNavigationStyle
{
    [self setNavigationBarTitle:@"二维码"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
